using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.Ram_Files;
using MediatR;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.RamFiles
{
    /// <summary>
    /// 公羊档案初期状态修改命令处理器
    /// </summary>
    public class UpdateRamInitialstateCommandHandler : IRequestHandler<UpdateRamInitialstateCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<RamFile> _ramRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateRamInitialstateCommandHandler> _logger;

        public UpdateRamInitialstateCommandHandler(
            IBaseRepository<RamFile> ramRepository,
            IMapper mapper,
            ILogger<UpdateRamInitialstateCommandHandler> logger)
        {
            _ramRepository = ramRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理公羊档案初期状态修改命令
        /// </summary>
        /// <param name="request">初期状态修改命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>修改结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateRamInitialstateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("公羊档案初期状态修改请求参数为空");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "请求参数不能为空", data = false };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"公羊档案初期状态修改数据验证失败: {errorMessage}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = errorMessage, data = false };
                }

                // 根据ID查询公羊档案
                var ramFile = await _ramRepository.GetByIdAsync(request.RamId);
                
                if (ramFile == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.RamId} 的公羊档案");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "未找到指定的公羊档案", data = false };
                }

                // 检查是否已被删除
                if (ramFile.IsDeleted)
                {
                    _logger.LogWarning($"ID为 {request.RamId} 的公羊档案已被删除");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "公羊档案已被删除", data = false };
                }

                // 执行初期状态修改
                ramFile.Initialstate = request.Initialstate;
                var result = await _ramRepository.UpdateAsync(ramFile);
                
                if (result > 0)
                {
                    _logger.LogInformation($"成功修改公羊档案初期状态，ID: {request.RamId}，新状态: {request.Initialstate}");
                    return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "公羊档案初期状态修改成功", data = true };
                }
                else
                {
                    _logger.LogError($"修改公羊档案初期状态失败，ID: {request.RamId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "公羊档案初期状态修改失败", data = false };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改公羊档案初期状态时发生系统异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "系统异常，请联系管理员", data = false };
            }
        }
    }
}